<?php
/**
 * Created by 老吴.
 * UserMsg:砥砺前行，扬帆起航
 * email:cwwx0128@qq.com
 * QQ:1113249273
 * QQ群:925283872
 * 微信:cww0128
 * Date: 2021/4/15
 * Time: 23:08
 */

namespace app\api\controller;

use app\common\controller\Api;
use think\Loader;

class AliMinappLogin extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $appId;
    protected $gatewayUrl;
    protected $rsaPrivateKey;
    protected $alipayrsaPublicKey;

    public function __construct()
    {
        $this->appId = get_addon_config("alilogin")['ali_app_id'];
        $this->gatewayUrl = get_addon_config("alilogin")['ali_gatewayUrl'];
        $this->rsaPrivateKey = get_addon_config("alilogin")['ali_rsaPrivateKey'];
        $this->alipayrsaPublicKey = get_addon_config("alilogin")['ali_alipayrsaPublicKey'];
        parent::__construct();
    }

    //开发参考地址文档
    //https://blog.csdn.net/qq_45163122/article/details/104185435
    //https://blog.csdn.net/qq_45163122/article/details/104148904


    public function test()
    {
        Loader::import('Hello', APP_PATH . '../addons/alilogin/extend/');
        $t = new \Hello();
        $t->test();
    }

    /**
     * 用户登录
     */
    public function login()
    {

//        $this->success('', get_addon_config("alilogin"));
        Loader::import('aliapo.AopClientSelf', APP_PATH . '../addons/alilogin/extend/');
        Loader::import('aliapo.request.AlipaySystemOauthTokenRequestSelf', APP_PATH . '../addons/alilogin/extend/');
//        $this->success('', $param);
        $aop = new \AopClientSelf();
        $param = $this->request->param();

        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = $this->appId;
        $aop->rsaPrivateKey = $this->rsaPrivateKey;
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $request = new \AlipaySystemOauthTokenRequestSelf();
        $request->setGrantType("authorization_code");
        $request->setCode($param['code']);
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $accessToken = $result->$responseNode->access_token;
        $ret = self::getUserInfoAli($accessToken);

//        $this->success('', $ret);
        if ($ret->alipay_user_info_share_response->code == '10000') {
            $userinfo = \app\admin\model\User::where(['openid' => $ret->alipay_user_info_share_response->user_id])->find();
            if ($userinfo) {
                $userinfo->nickname = $ret->alipay_user_info_share_response->nick_name;
                $userinfo->avatar = $ret->alipay_user_info_share_response->avatar;
                $userinfo->gender = $ret->alipay_user_info_share_response->gender == 'm' ? '1' : '0';
                $userinfo->city = $ret->alipay_user_info_share_response->city;
                $userinfo->province = $ret->alipay_user_info_share_response->province;
                $userinfo->country = '中国';
                $userinfo->save();
                $this->auth->direct($userinfo['id']);
            } else {
                $user = new \app\admin\model\User();
                $user->data([
                    'nickname' => $ret->alipay_user_info_share_response->nick_name,
                    'avatar' => $ret->alipay_user_info_share_response->avatar,
                    'gender' => $ret->alipay_user_info_share_response->gender == 'm' ? '1' : '0',
                    'city' => $ret->alipay_user_info_share_response->city,
                    'province' => $ret->alipay_user_info_share_response->province,
                    'country' => '中国',
                    'status' => 'normal',
                    'openid' => $ret->alipay_user_info_share_response->user_id
                ]);
                $user->save();
                $this->auth->direct($user->id);
            }
            $this->success('登录成功', $this->auth->getUserinfo());
        } else {
            $this->error($ret->alipay_user_info_share_response->msg . '错误码：' . $ret->alipay_user_info_share_response->code);
        }

    }


    /**
     * 获取支付宝用户信息
     * @param $accessToken
     */
    protected function getUserInfoAli($accessToken)
    {
        Loader::import('aliapo.AopClientSelf', APP_PATH . '../addons/alilogin/extend/');
        Loader::import('aliapo.request.AlipayUserInfoShareRequestSelf', APP_PATH . '../addons/alilogin/extend/');
        $aop = new \AopClientSelf ();
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = $this->appId;
        $aop->rsaPrivateKey = $this->rsaPrivateKey;
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $request = new \AlipayUserInfoShareRequestSelf ();
        $result = $aop->execute($request, $accessToken);
        return $result;
    }

}